const path = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

const resolve = (...args) => path.resolve(__dirname, ...args)

console.log('当前的环境是：', process.env.NODE_ENV)
module.exports = {
  mode: process.env.NODE_ENV,
  entry: './src/index.js',
  output: {
    filename: './src/[contenthash:8].index.js',
    path: resolve('build'),
    publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx|ts|tsx)$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.(js|jsx|ts|tsx)$/,
        loader: 'eslint-loader',
        exclude: /node_modules/,
        enforce: 'pre'
      },
      {
        test: /\.[(png)|(obj)|(json)]$/,
        loader: 'file-loader'
      },
      {
        test: /\.(woff|woff2|jpg|png)$/,
        use: {
          loader: 'url-loader',
          options: {
            name: 'imanges/[hash].[ext]',
            limit: 5000,
            mimetype: 'application/font-woff'
          }
        }
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader']
      },
      {
        test: /\.less$/,
        use: [
          MiniCssExtractPlugin.loader,
          { loader: 'css-loader', options: { sourceMap: false } },
          {
            loader: 'less-loader',
            options: {
              lessOptions: {
                strictMath: true,
                noIeCompat: true
              }
            }
          }
        ]
      }
    ]
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
    alias: {
      '@': resolve('./src'),
      components: resolve('./src/components'),
      pages: resolve('./src/pages'),
      common: resolve('./src/common'),
      store: resolve('./src/store'),
      api: resolve('./src/api')
    }
  },
  devtool: process.env.NODE_ENV === 'production' ? false : 'inline-source-map',
  devServer: {
    contentBase: resolve('src'),
    publicPath: '/',
    compress: true,
    port: 8080,
    host: 'localhost',
    historyApiFallback: true
    // historyApiFallback: true // 解决404问题
  },
  plugins: [
    new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns: './build' // 打包时清除build目录
    }),
    new MiniCssExtractPlugin({
      filename: 'css/[contenthash:8].css'
    }),
    new HtmlWebpackPlugin({
      template: './template/index.html'
    })
  ]
}
